<?php

defined('SYSPATH') or die('No direct script access.');

class Formtable {

    private static $instances;
    private $data;

    public static function & instances($id = 0) {

        if (!isset(self::$instances[$id])) {
            $class = __CLASS__;
            self::$instances[$id] = new $class($id);
        }
        return self::$instances[$id];
    }

    public function __construct($id) {

        $this->data = NULL;
        $this->_load($id);
    }

    public function _load($id) {

        if (!$id)
            return FALSE;

        $result = ORM::factory('formtable')
                ->where('id', '=', $id)
                ->find()
                ->as_array();

        $this->data = $result ? $result : array();
    }

    public function get($key = NULL) {

        if (is_null($key)) {
            return $this->data;
        } else {
            return isset($this->data[$key]) ? $this->data[$key] : NULL;
        }
    }

    public function set($data) {

        $formtable = ORM::factory('formtable');
        $formtable->values($data);
        if ($formtable->check()) {
            $formtable->save();
            if ($formtable->saved()) {
                return true;
            }
        }
        return false;
    }

  

    public function update($data) {
        $formtable = ORM::factory('formtable')
                ->where('id', '=', $this->data['id'])
                ->find();

        if (!$formtable->loaded()) {
            return false;
        } else {
            $formtable->values($data);
            if ($formtable->check()) {
                $formtable->save();
                if ($formtable->saved()) {
                    return true;
                }
            }
        }
    }

    public function delete() {
        $formtable = ORM::factory('formtable', $this->data['id']);
        if ($formtable->loaded()) {
            return $formtable->delete();
        } else {
            return FALSE;
        }
    }
    
    
    public function get_formtable_by_tablename($tablename = '') {
        
        
        $formtable = ORM::factory('formtable')
                ->where('ft_tablename','=',$tablename)
                ->find()
                ->as_array();
        
        
        if(count($formtable)>0) {
            return $formtable;
        }
        
        
    }


}

